﻿using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SmartProduction.ErrorCode;
using SmartProduction.Write.API.Application.Commands.ProductionOrdersCommand;

namespace SmartProduction.Write.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ProductionOrdersController : ControllerBase
    {
        private readonly IMediator mediator;

        public ProductionOrdersController(IMediator mediator)
        {
            this.mediator = mediator;
        }
        /// <summary>
        /// 生产工单添加
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<object>> ProductionOrdersCreate(ProductionOrdersCreateCommand request)
        {
            try
            {
                return await mediator.Send(request);
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="attachment"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CoverImage(IFormFile attachment)
        {
            try
            {
                // 确保上传目录存在
                var uploadPath = Path.Combine("wwwroot", "img");
                if (!Directory.Exists(uploadPath)) Directory.CreateDirectory(uploadPath);

                // 生成唯一文件名防止覆盖
                var fileName = $"{Guid.NewGuid()}{Path.GetExtension(attachment.FileName)}";
                var filePath = Path.Combine(uploadPath, fileName);

                // 保存文件
                await using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await attachment.CopyToAsync(stream);
                }

                // 返回可直接访问的图片地址
                return Ok(new
                {
                    code = 200,
                    data = $"/img/{fileName}" // 返回相对路径
                });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { code = 500, message = ex.Message });
            }
        }

    }
}
